package com.jch.watermaker;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;
import java.time.Duration;
import java.util.Random;
import java.util.UUID;

public class WatermakerDemo02_AllowedLateness {


    public static void main(String[] args) throws Exception{

        //创建运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2.source
        //模拟实时订单数据
        DataStreamSource<Order> source = env.addSource(new SourceFunction<Order>() {
            private boolean flag = true;

            @Override
            public void run(SourceContext<Order> order) throws Exception {
                Random random = new Random();
                while (flag) {
                    String orderId = UUID.randomUUID().toString();
                    int userId = random.nextInt(3);
                    int money = random.nextInt(100);
                    //模拟数据延迟和乱序
                    long eventTime = System.currentTimeMillis() - random.nextInt(10) * 1000;
                    order.collect(new Order(orderId, userId, money, eventTime));

                }
            }

            @Override
            public void cancel() {
                flag = false;
            }
        });

        //3.Transformation
        SingleOutputStreamOperator<Order> orderDS = source.assignTimestampsAndWatermarks(
                WatermarkStrategy.<Order>forBoundedOutOfOrderness(
                        Duration.ofSeconds(3)).
                        withTimestampAssigner((event, timestamp) ->
                                event.getEventTime()));


        //代码添加上watermaker
        //要求每隔5s内（基于时间的滚动窗口） 每个用户订单金额
        OutputTag<Order> outputTag = new OutputTag<>("Seriouslyate", TypeInformation.of(Order.class));

        SingleOutputStreamOperator<Order> result = orderDS.
                keyBy(Order::getUserId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .allowedLateness(Time.seconds(5))
                .sideOutputLateData(outputTag)
                .sum("money");

        DataStream<Order> sideOutput = result.getSideOutput(outputTag);

        //4.sink
        //result.print("正常的数据和不迟到的数据");
        sideOutput.print("严重迟到的数据");

        //5.execute
        env.execute();


    }




    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Order{

        private String orderId;
        private Integer userId;
        private Integer money;
        private Long eventTime;

    }


}
